<template>
  <div class="language-switcher">
    <el-dropdown @command="switchLanguage" trigger="click">
      <span class="switcher-text">
        {{ currentLanguageDisplay }}
        <el-icon class="el-icon--right"><ArrowDown /></el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item :command="LANGUAGES.ZH" :disabled="isCurrentLanguage(LANGUAGES.ZH)">
            中文
          </el-dropdown-item>
          <el-dropdown-item :command="LANGUAGES.EN" :disabled="isCurrentLanguage(LANGUAGES.EN)">
            English
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { getCurrentLanguage, changeLanguage, LANGUAGES } from '../utils/i18n'

// 语言显示名称
const languageLabels = {
  [LANGUAGES.ZH]: '中文',
  [LANGUAGES.EN]: 'English'
}

// 当前语言
const currentLang = ref(getCurrentLanguage())

// 监听语言变化事件
onMounted(() => {
  // 确保组件挂载时获取正确的当前语言
  currentLang.value = getCurrentLanguage()
  
  const handleLanguageChange = (event) => {
    if (event.detail && event.detail.lang) {
      currentLang.value = event.detail.lang
    }
  }
  
  // 添加事件监听
  window.addEventListener('language-changed', handleLanguageChange)
  
  // 组件卸载时移除监听
  return () => {
    window.removeEventListener('language-changed', handleLanguageChange)
  }
})

// 当前语言显示名称
const currentLanguageDisplay = computed(() => {
  return languageLabels[currentLang.value] || languageLabels[LANGUAGES.ZH]
})

// 判断是否是当前语言
const isCurrentLanguage = (lang) => {
  return currentLang.value === lang
}

/**
 * 切换语言
 * @param {string} lang - 目标语言代码
 */
const switchLanguage = (lang) => {
  if (isCurrentLanguage(lang)) return
  
  if (changeLanguage(lang)) {
    currentLang.value = lang
    ElMessage.success(`已切换到${languageLabels[lang]}`)
    // 刷新页面以应用新语言 - 增加日志便于调试
    setTimeout(() => {
      window.location.reload()
    }, 500)
  } else {
    ElMessage.error('语言切换失败')
  }
}
</script>

<style scoped>
.language-switcher {
  display: inline-block;
}

.switcher-text {
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.el-icon--right {
  margin-left: 5px;
}
</style> 